package com.itheima.health.jobs;

import com.itheima.health.common.RedisConst;
import com.itheima.health.utils.QiniuUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

/**
 * @Author likepei
 * @Date 2020/4/2 0:09
 * @Version v1.0
 * @Description 清除数据工作的任务类
 */
public class ClearJob {

    //依赖注入一个Jedis
    @Autowired
    private JedisPool jedisPool;

    /**
     * 清空垃圾图片的方法
     */
    public void clearImageJob(){
        System.out.println("clearImageJob==============");
        //获取所有的图片名称
        Set<String> imgNames  = jedisPool.getResource().smembers(RedisConst.SETMEAL_PIC_RESOURCES);
        //获取昨天的日期字符串
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -1);
        Date yesterday = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String str = sdf.format(yesterday);
        //开始删除
        for (String imgName : imgNames) {
            //如果以昨天的日期开头则可以删除
            if(imgName != null && imgName.startsWith(str)){
                //删除昨天的图片
                delQiniu(imgName);
                //删除redis中的图片名称
                jedisPool.getResource().srem(RedisConst.SETMEAL_PIC_RESOURCES, imgName);
                System.out.println("删除了" + imgName + "图片!!");
            }
        }
    }
    /**
     * 删除七牛图片的方法
     */
    public void delQiniu(String imgName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        String key = imgName;
        Auth auth =
                Auth.create("OQJOgdODNFYRke0BmDH19ztL8OpYrYKrxucUajn0", "lXIWT8mzMuCeDQVz-mRfrMGE8f-F_ksQRYQJw_SQ");
        BucketManager bucketManager = new BucketManager(auth, cfg);
            try {
            bucketManager.delete("itcasthealth359", key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }

    }

    /**
     * 清空垃圾文件的方法
     */
    public void clearFileJob(){

        System.out.println("clearFileJob.....");
    }
}
